package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.OrganizationService;
import com.juzhencms.apps.common.interceptor.UserInterceptor;

import lombok.extern.slf4j.Slf4j;

import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.MD5Util;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

@Controller
@RequestMapping("/checkRuleItem")
@Slf4j
public class CheckRuleItemController  extends BaseController{
	@Autowired
	private OrganizationService organizationService;
	//查询所有用户
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 ";
		//搜索参数
		String searchVar=null;
		String varValue=null;
		if(request.getParameter("varValue")!=null && !request.getParameter("varValue").toString().trim().equals("")){
			
			if(request.getParameter("searchVar")!=null && !request.getParameter("searchVar").toString().trim().equals("")){
				searchVar=request.getParameter("searchVar");
				if("create_user".equals(searchVar)){
					varValue=request.getParameter("varValue");
					Map record=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.user+" where user=?",new Object[]{varValue});	
					if(record != null){
						where += " and create_user = " + record.get("id");
					}else{
						data.put("data", "");
						return WebUtil.resultString(data,request);
					}
				}else{
					whereParamList.add("%"+request.getParameter("varValue")+"%");
					where += " and "+searchVar+" like ? ";
				}
				
			}else{
				where+=" and name like ? ";
			}
		}
		
		if( StringUtil.isNotNullOrEmpty(request.getParameter("checkRuleId").toString().trim()) && !request.getParameter("checkRuleId").equals("0")){
			where+=" and check_rule_id = ? ";
			whereParamList.add(request.getParameter("checkRuleId"));
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=100;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		

		//查询列表数据
		//System.out.println("select * from "+DBTable.checkRule+" "+where+" order by "+sortField+" "+sortOrder+",create_time desc,id desc limit ?,?");
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.checkRuleItem+" "+where+" order by position asc,id asc limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
				
				Date updatedate = (Date)row.get("update_time");
				row.put("update_time",sdf.format(updatedate));
				//更新人
				if(StringUtil.isNotNullOrEmpty(row.get("update_user")) && !"0".equals(row.get("update_user"))) {
					Map userData=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where id=?",new Object[]{row.get("update_user")});
					if(userData !=null) {
					   row.put("update_user",userData.get("name"));
					}
				}
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRuleItem+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		return WebUtil.resultString(data,request);
	}
	
	

	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where id=?",new Object[]{id});	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		//查询可流转的规则
		if(record.get("move_rules")!=null && !record.get("move_rules").equals("")) {
			String[] ids=record.get("move_rules").toString().split(",");
			List tmpSqlParam=new ArrayList();
			for(int i=0;i<ids.length;i++) {
				tmpSqlParam.add("?");
			}
			List moveRuleList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.checkRule+" where del_flag=0 and id in ("+org.apache.commons.lang3.StringUtils.join(tmpSqlParam.toArray(), ",")+")", ids);
			if(moveRuleList!=null) {
				for(int i=0;i<moveRuleList.size();i++){
					Map row=(Map)moveRuleList.get(i);
					//节点数
					Map ruleItemCount=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRuleItem+" where check_rule_id=?",new Object[] {row.get("id")});
					int nodeNums=0;
					if(ruleItemCount.get("count_num")!=null){
						nodeNums=new Integer(ruleItemCount.get("count_num").toString()).intValue();
					}
					row.put("nodeNums",nodeNums);
				}
			}
			data.put("moveRuleList", moveRuleList);
		}
		
		
		return WebUtil.resultString(data,request);
	}
	

	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		//机构org_id
		if(StringUtil.isNullOrEmpty(data.get("org_id"))) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "保存失败，请选择所属机构");
			return WebUtil.resultString(result,request);
		} else {
			int org_id = new Integer(data.get("org_id").toString());
			if(org_id <=0) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "保存失败，请选择所属机构");
				return WebUtil.resultString(result,request);
			}
			//机构名称  
			Map getRule = this.getCommonService().getJdbcDao().queryRow("select name from "+DBTable.role+" where id=? ",new Object[]{data.get("role_id")});
			if(getRule!=null && !getRule.get("name").equals("") ) {
				data.put("role_name",getRule.get("name"));
			}
			
		}
		
		//如果是批注类型，自动设置为可同步执行
		if(data.get("type")!=null && data.get("type").toString().equals("1")) {
			data.put("asyn", 1);
			//如果是批注类型，不允许流转和会签
			data.put("allow_move", 0);
			data.put("allow_countersign", 0);
		}else {
			data.put("asyn", 0);
		}
		
		if(id==null || id.equals("")){
			Date date = new Date();
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				data.put("create_time", sdf.format(date));
				data.put("update_time", sdf.format(date));
			}
			data.put("create_user", this.getLoginUserId());
			data.put("update_user", this.getLoginUserId());
			data.put("position", date.getTime());
			this.getCommonService().getJdbcDao().addObj(DBTable.checkRuleItem, data);
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			data.put("update_time", sdf.format(date));
			data.put("update_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().updateObj(DBTable.checkRuleItem, data, "id");
		}
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}

	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set del_flag=1 where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	//更新发布状态
	@RequestMapping(value="/updatePublish",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePublish(HttpServletRequest request){
		String num = "1".equals(request.getParameter("publish"))?"0":"1";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set publish=? where id=?",new Object[]{num,request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/upAutoPosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String upAutoPosition(HttpServletRequest request){
		
		String id=request.getParameter("id");
		
		//查询当前新闻
		Map thisNews=this.getCommonService().getJdbcDao().queryRow("select id,check_rule_id,position from "+DBTable.checkRuleItem+" where id=?", new Object[] {id});
		
		//查询上一条新闻
		Map prevNews=this.getCommonService().getJdbcDao().queryRow("select id,position from "+DBTable.checkRuleItem+" where check_rule_id=? and position<=? and id!=? and del_flag=0 order by position desc limit 0,1", new Object[] {thisNews.get("check_rule_id"),thisNews.get("position"),id});
		
		
		
		
		
		if(prevNews!=null) {
			//如果两条数据的排序位置相差超过2，则交换并且减1，以避免有排序号重复的数据
			if(Long.parseLong(prevNews.get("position").toString())-Long.parseLong(thisNews.get("position").toString())>2) {
				
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(prevNews.get("position").toString())+1,thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString())-1,prevNews.get("id")});
				
				
			}else {//否则交换排序号
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(prevNews.get("position").toString()),thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString()),prevNews.get("id")});
				
			}
		}
		
		
		
		
	
		
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/downAutoPosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String downAutoPosition(HttpServletRequest request){
		String id=request.getParameter("id");
		
		//查询当前新闻
		Map thisNews=this.getCommonService().getJdbcDao().queryRow("select id,check_rule_id,position from "+DBTable.checkRuleItem+" where id=?", new Object[] {id});
		
		//查询上一条新闻
		Map nextNews=this.getCommonService().getJdbcDao().queryRow("select id,position from "+DBTable.checkRuleItem+" where check_rule_id=? and position>=? and id!=? and del_flag=0 order by position asc limit 0,1", new Object[] {thisNews.get("check_rule_id"),thisNews.get("position"),id});
		
		
		
		if(nextNews!=null) {
			//如果两条数据的排序位置相差超过2，则交换并且减1，以避免有排序号重复的数据
			if(Long.parseLong(thisNews.get("position").toString())-Long.parseLong(nextNews.get("position").toString())>2) {
				
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(nextNews.get("position").toString())-1,thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString())+1,nextNews.get("id")});
				
				
			}else {//否则交换排序号
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(nextNews.get("position").toString()),thisNews.get("id")});
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.checkRuleItem+" set position=? where id=?",new Object[]{Long.parseLong(thisNews.get("position").toString()),nextNews.get("id")});
				
			}
		}
		
		
		
	
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
}
